package com.lt.app;

import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;


/**
 * 数据共享类
 */
public class DataHolder {

    private static DataHolder instance;
    //短生命周期
    private Map<String, WeakReference<Object>> data = new HashMap<>();
    //长生命周期
    private Map<String, SoftReference<Object>> dataL = new HashMap<>();

    private DataHolder() {
    }

    public static DataHolder getInstance() {
        if (instance == null) {
            synchronized (DataHolder.class) {
                instance = new DataHolder();
            }
        }
        return instance;
    }

    public void setData(String id, Object object) {
        data.put(id, new WeakReference<>(object));
    }

    public Object getData(String id) {
        WeakReference<Object> objectWeakReference = data.get(id);
        if (objectWeakReference != null) {
            return objectWeakReference.get();
        }
        return null;
    }

    public void remove(String key) {
        if (data != null) {
            data.remove(key);
        }
    }

    public void setDataL(String id, Object object) {
        dataL.put(id, new SoftReference<>(object));
    }

    public Object getDataL(String id) {
        SoftReference<Object> softReference = dataL.get(id);
        if (softReference != null) {
            return softReference.get();
        }
        return null;
    }

    public void removeL(String key) {
        if (dataL != null) {
            dataL.remove(key);
        }
    }

    public void clear() {
        if (data != null) {
            data.clear();
        }
        if (dataL != null) {
            dataL.clear();
        }
    }

}
